package com.by.common.controller;

import com.by.common.bean.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 江俊俊
 * @version 1.0
 * @description
 * @date 2025/2/14 20:41
 * @since JDK1.8
 */
@RestController
public class UploadController extends BaseController {

    final String ROOT = "/attach";

    @Autowired
    HttpServletRequest request;

    Set<String> types;

    @PostConstruct
    public void init() {
        types = new HashSet<>();
        types.add("image/jpg");
        types.add("image/png");
    }

    public ResultBean batchUpload(List<MultipartFile> files) {
        if (files == null || files.size() == 0) {
            return new ResultBean<>(0, "请选择上传的文件", null);
        }
        final Map map = new HashMap();
        files.forEach(e -> {
            ResultBean resultBean = upload(e);
            map.put(e.getOriginalFilename(), resultBean);
        });
        return success("上传结果", map);
    }

    @PostMapping("/upload")
    public ResultBean upload(MultipartFile file) {
        //限制文件类型
        //获取文件类型
        String type = file.getContentType();
        if (types.contains(type)) {
            return new ResultBean<>(0, "请上传jpg、png格式", null);
        }

        //获取新的文件名
        String name = getNewFileName(file.getOriginalFilename());
        //获取服务器根目录
        DisDir dir = getDisDir();
        //上传文件
        try {
            file.transferTo(new File(dir.getRoot()+dir.getRelativePath(),name));
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return success("上传成功",dir.getRelativePath()+"/"+name);
    }

    /**
     * 获取新的文件名
     * @param fileName
     * @return
     */
    String getNewFileName(String fileName) {
        int pos = fileName.lastIndexOf(".");
        String ext = fileName.substring(pos);
        String newFileName = System.currentTimeMillis() +ext;
        return newFileName;
    }

    /**
     * 获取上传的附件的存储目录
     * @return
     */
    DisDir getDisDir() {
        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/");
        //获取当前日期
        String date = getSysYMD();
        File file = new File(root + ROOT + "/" + date);
        if (!file.exists()) {
            file.mkdirs();
        }
        return new DisDir(root, ROOT + "/" + date);

    }

    class DisDir {
        String root;
        String relativePath;

        public DisDir(String root, String relativePath) {
            this.root = root;
            this.relativePath = relativePath;
        }

        public String getRoot() {
            return root;
        }

        public void setRoot(String root) {
            this.root = root;
        }

        public String getRelativePath() {
            return relativePath;
        }

        public void setRelativePath(String relativePath) {
            this.relativePath = relativePath;
        }
    }

    /**
     * 获取系统当前日期
     * @return
     */
    String getSysYMD() {
        LocalDate now = LocalDate.now();
        return now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }
}
